package com.hongtech.tiny.modules.app.controller;

import com.hongtech.tiny.common.response.ObjectResult;
import com.hongtech.tiny.common.response.ResultCode;
import com.hongtech.tiny.modules.app.annotation.Login;
import com.hongtech.tiny.modules.app.annotation.LoginUser;
import com.hongtech.tiny.modules.app.form.AuthForm;
import com.hongtech.tiny.modules.app.form.EditPasswordForm;
import com.hongtech.tiny.modules.app.form.LoginForm;
import com.hongtech.tiny.modules.app.utils.AppJwtUtils;
import com.hongtech.tiny.modules.knowledge.entity.AuthEntity;
import com.hongtech.tiny.modules.knowledge.entity.UserEntity;
import com.hongtech.tiny.modules.knowledge.service.AuthService;
import com.hongtech.tiny.modules.knowledge.service.UserService;
import com.hongtech.tiny.modules.oss.entity.LocalFileEntity;
import com.hongtech.tiny.modules.oss.service.LocalFileService;
import com.hongtech.tiny.modules.oss.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app")
@Api(tags = "登录接口")
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private AppJwtUtils appJwtUtils;

    @Resource
    private AuthService authService;

    @Resource
    private LocalFileService localFileService;

    @PostMapping("login")
    @ApiOperation("会员登录")
    public ObjectResult<Map<String, Object>> login(@RequestBody LoginForm form) {
        UserEntity user = userService.getUserInfoByMobile(form.getMobile());
        if (ObjectUtils.isEmpty(user)) {
            return ObjectResult.failed(ResultCode.FAILED, "手机号或密码错误");
        }
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            return ObjectResult.failed(ResultCode.FAILED, "手机号或密码错误");
        }
        // 返回屏蔽密码字段
        user.setPassword(null);
        String token = appJwtUtils.getAppToken(user);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);
        return ObjectResult.success(map);
    }

    @Login
    @PostMapping("saveUserInfo")
    @ApiOperation("保存个人资料")
    public ObjectResult<String> saveUserInfo(@LoginUser UserEntity user, @RequestBody UserEntity params) {
        if (ObjectUtils.isEmpty(user.getId())) {
            return ObjectResult.validateFailed();
        }
        params.setId(user.getId());
        if(userService.updateById(params)) {
            return ObjectResult.success();
        }
        return ObjectResult.failed("保存失败！");
    }

    @Login
    @GetMapping("getUserInfo")
    @ApiOperation("获取个人资料")
    public ObjectResult<UserEntity> getUserInfo(@LoginUser UserEntity user) {
        if (ObjectUtils.isEmpty(user)) {
            return ObjectResult.validateFailed();
        }
        return ObjectResult.success(user);
    }

    @Login
    @PostMapping("editPassword")
    @ApiOperation("修改密码")
    public ObjectResult<String> editPassword(@LoginUser UserEntity user, @RequestBody EditPasswordForm editPasswordForm) {
        if (ObjectUtils.isEmpty(user.getId())) {
            return ObjectResult.validateFailed();
        }
        UserEntity appUser = userService.getById(user.getId());
        if (!appUser.getPassword().equals(DigestUtils.sha256Hex(editPasswordForm.getOldPassword()))) {
            return ObjectResult.failed(ResultCode.FAILED, "旧的错误密码！");
        }
        appUser.setPassword(DigestUtils.sha256Hex(editPasswordForm.getNewPassword()));
        if(userService.updateById(appUser)) {
            return ObjectResult.success();
        }
        return ObjectResult.failed("修改密码失败！");
    }

    @Login
    @PostMapping("saveUserAvatar")
    @ApiOperation("修改头像")
    public ObjectResult<?> saveUserAvatar(MultipartFile file, @LoginUser UserEntity user) {
        if (file == null) {
            return ObjectResult.failed("头像上传失败！");
        }
        String fileName = FileUtils.getFileNameNoEx(file.getOriginalFilename());
        LocalFileEntity localFileEntity = localFileService.create(fileName, file);
        UserEntity avatarUser = new UserEntity();
        avatarUser.setId(user.getId());
        avatarUser.setHeadPic(localFileEntity.getType() + "/" + localFileEntity.getRealName());
        if(userService.updateById(avatarUser)) {
            return ObjectResult.success(avatarUser.getHeadPic());
        }
        return ObjectResult.failed("头像上传失败！");
    }

    @Login
    @PostMapping("saveUserAuth")
    @ApiOperation("保存认证信息")
    public ObjectResult<String> saveUserAuth(AuthForm authForm, @LoginUser UserEntity user) {
        AuthEntity oldAuth = authService.getUserAuthByUserId(user.getId());
        AuthEntity newAuth = new AuthEntity();
        if (ObjectUtils.isNotEmpty(authForm.getFrontPic())) {
            String fileName = FileUtils.getFileNameNoEx(authForm.getFrontPic().getOriginalFilename());
            LocalFileEntity localFileEntity = localFileService.create(fileName, authForm.getFrontPic());
            newAuth.setFrontPic(localFileEntity.getType() + "/" + localFileEntity.getRealName());
        }
        if (ObjectUtils.isNotEmpty(authForm.getBackPic())) {
            String fileName = FileUtils.getFileNameNoEx(authForm.getBackPic().getOriginalFilename());
            LocalFileEntity localFileEntity = localFileService.create(fileName, authForm.getBackPic());
            newAuth.setBackPic(localFileEntity.getType() + "/" + localFileEntity.getRealName());
        }
        newAuth.setIdCard(authForm.getIdCard());
        newAuth.setCityId(authForm.getCityId());
        newAuth.setCityName(authForm.getCityName());
        newAuth.setUserId(user.getId());
        if (ObjectUtils.isNotEmpty(oldAuth)) {
            newAuth.setId(oldAuth.getId());
            authService.updateById(newAuth);
        } else {
            authService.save(newAuth);
        }
        // 变更认证状态-->认证中
        UserEntity authUser = new UserEntity();
        authUser.setId(user.getId());
        authUser.setAuthStatus(1);
        userService.updateById(authUser);
        return ObjectResult.success();
    }

    @Login
    @GetMapping("getUserAuth")
    @ApiOperation("获取认证信息")
    public ObjectResult<AuthEntity> getUserAuth(@LoginUser UserEntity user) {
        if (ObjectUtils.isEmpty(user.getId())) {
            return ObjectResult.validateFailed();
        }
        AuthEntity auth = authService.getUserAuthByUserId(user.getId());
        return ObjectResult.success(auth);
    }

}
